class CommandController < ApplicationController
  verify :method => :post, :only => [ :destroy, :cancel_mission ],
         :redirect_to => { :controller => 'command', :action => 'index' }

  before_filter :authorize_admin, :only => []
  
  def index
    user = cookies[:SMFUser]
    @member = Member.find_by_smf_name(user)
    
    session[:member_id] = @member.id

    @available_missions = Mission.find(:all, :conditions => "UNIX_TIMESTAMP(start_date) > #{Time.now.to_i}")
    if(@available_missions.nil?)
      @available_missions = []
    end

    my_missions = []
    for m in @available_missions
      msn_regs = MissionRegistration.find(:all, :conditions => "mission_id = #{m.id} and member_id = #{@member.id} and #{m.start_date.to_i}  > #{Time.now.to_i}")
      if(msn_regs.nil?)
        next
      end
      msn_regs = msn_regs.to_a
      if(msn_regs.length > 0)
          for reg in msn_regs
            my_missions.push Mission.find(reg.mission_id)
          end
      end
     end
    @my_upcoming_missions = my_missions.select { |m| m.start_date > Time.now }
    @my_upcoming_missions.sort! { |x,y| x.start_date <=> y.start_date }

    @available_missions -= @my_upcoming_missions
  end
  
  def new_character
    @member = Member.find(session[:member_id])
    if(@member.characters.count == 16)
      flash[:notice] = 'You already have the maximum 16 characters'
    else
      @member.characters << Character.for_member(@member)
      @member.save
    end
    redirect_to :action => 'index'
  end
  
  def cancel_mission
    MissionRegistration.find_by_mission_id(params[:id]).to_a.each { |e| e.destroy }
    Mission.find(params[:id]).destroy
    redirect_to :controller => 'command', :action => 'index'
  end
end